<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useThemeStore } from '../stores/theme'; // Ensure path is correct

const themeStore = useThemeStore();

// --- Refs ---
const stripRef = ref(null); // Ref for the hue strip element
const isDragging = ref(false);

// --- Fixed Saturation and Lightness (Adjustable) ---
const saturation = 85; // Saturation (0-100)
const lightness = 60; // Lightness (0-100)

// --- Default Hue ---
const DEFAULT_HUE = 180;
const defaultHexColor = computed(() => hslToHex(DEFAULT_HUE, saturation, lightness)); // Calculate default hex once

// --- Computed property for current HSL ---
const currentHsl = computed(() => {
  const hex = themeStore.primaryColor;
  return hexToHsl(hex);
});

// --- Computed property for current Hue (rounded) ---
const currentHue = computed(() => {
  // Use the calculated HSL, default to DEFAULT_HUE if conversion fails
  return currentHsl.value ? Math.round(currentHsl.value.h) : DEFAULT_HUE;
});

// --- Computed property for marker position ---
const markerPosition = computed(() => {
  // Map hue (0-360) to percentage (0-100)
  const percentage = (currentHue.value / 360) * 100;
  return `${percentage}%`;
});

// --- Computed property to show Reset Button ---
const showResetButton = computed(() => {
  // Show if the current hue is different from the default hue
  return currentHue.value !== DEFAULT_HUE;
});


// --- Event Handlers ---
function handleInteraction(event) {
  if (!stripRef.value) return;

  const rect = stripRef.value.getBoundingClientRect();
  // Handle both mouse and touch events
  const clientX = event.type.startsWith('touch') ? event.touches[0].clientX : event.clientX;
  let relativeX = clientX - rect.left;

  // Clamp position within the strip bounds
  relativeX = Math.max(0, Math.min(relativeX, rect.width));

  const percentage = relativeX / rect.width;
  const hue = Math.round(percentage * 360);

  // Generate new color based on selected hue and fixed S/L
  const newHexColor = hslToHex(hue, saturation, lightness);
  themeStore.setPrimaryColor(newHexColor);
}

function startDrag(event) {
  // Prevent text selection during drag on desktop
  if (event.type === 'mousedown') {
      event.preventDefault();
  }
  isDragging.value = true;
  handleInteraction(event); // Update color immediately on press/touch
  // Add listeners to window for dragging outside the element
  window.addEventListener('mousemove', handleDrag);
  window.addEventListener('mouseup', stopDrag);
  window.addEventListener('touchmove', handleDrag, { passive: false }); // Passive false for touchmove preventDefault if needed later
  window.addEventListener('touchend', stopDrag);
}

function handleDrag(event) {
  if (isDragging.value) {
    // Prevent scrolling on touch devices while dragging
    if (event.type === 'touchmove') {
        event.preventDefault();
    }
    handleInteraction(event);
  }
}

function stopDrag() {
  if (isDragging.value) {
    isDragging.value = false;
    // Remove window listeners
    window.removeEventListener('mousemove', handleDrag);
    window.removeEventListener('mouseup', stopDrag);
    window.removeEventListener('touchmove', handleDrag);
    window.removeEventListener('touchend', stopDrag);
  }
}

function resetColor() {
  // Set color back to the default (Hue 250 with fixed S/L)
  themeStore.setPrimaryColor(defaultHexColor.value);
}

// --- Helper Functions (Color Conversion) ---
function hexToHsl(hex) {
    // Basic validation
    if (!hex || typeof hex !== 'string' || !hex.startsWith('#')) return { h: DEFAULT_HUE, s: saturation, l: lightness }; // Return default HSL on invalid input

    let r = 0, g = 0, b = 0;
    hex = hex.slice(1); // Remove #

    if (hex.length === 3) {
        r = parseInt(hex[0] + hex[0], 16);
        g = parseInt(hex[1] + hex[1], 16);
        b = parseInt(hex[2] + hex[2], 16);
    } else if (hex.length === 6) {
        r = parseInt(hex[0] + hex[1], 16);
        g = parseInt(hex[2] + hex[3], 16);
        b = parseInt(hex[4] + hex[5], 16);
    } else {
        return { h: DEFAULT_HUE, s: saturation, l: lightness }; // Return default HSL on invalid length
    }

    r /= 255; g /= 255; b /= 255;
    const max = Math.max(r, g, b), min = Math.min(r, g, b);
    let h = 0, s = 0, l = (max + min) / 2;

    if (max === min) {
        h = s = 0; // achromatic (gray)
    } else {
        const d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch (max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    // Return rounded HSL values
    return {
        h: Math.round(h * 360),
        s: Math.round(s * 100),
        l: Math.round(l * 100)
    };
}


function hslToHex(h, s, l) {
  h = h % 360; // Ensure hue is within 0-359
  s /= 100;
  l /= 100;
  let r, g, b;
  if (s === 0) {
    r = g = b = l; // achromatic
  } else {
    const hue2rgb = (p, q, t) => {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    };
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    const p = 2 * l - q;
    r = hue2rgb(p, q, h / 360 + 1 / 3);
    g = hue2rgb(p, q, h / 360);
    b = hue2rgb(p, q, h / 360 - 1 / 3);
  }
  const toHex = x => {
    const hex = Math.round(x * 255).toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  };
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();
}

// --- Lifecycle ---
onMounted(() => {
  // Optional: Set initial color if store is empty?
  // if (!themeStore.primaryColor) {
  //   themeStore.setPrimaryColor(defaultHexColor.value);
  // }
});
</script>

<template>
  <div class="palette-panel">
    <!-- Top Section -->
    <div class="panel-header">
      <div class="title-area">
        <span class="color-indicator-bar" :style="{ backgroundColor: themeStore.primaryColor }"></span>
        <h4>主题色</h4>
		<button v-if="showResetButton" class="reset-button" @click="resetColor" title="重置为默认颜色 (蓝)">
		  <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"  viewBox="0 0 24 24"><path fill="currentColor" d="M12 4c-4.42 0-8 3.58-8 8s3.58 8 8 8s8-3.58 8-8c0-.69-.09-1.36-.25-2h-1.73c.13.64.23 1.31.23 2c0 3.31-2.69 6-6 6s-6-2.69-6-6s2.69-6 6-6v4l4-4l-4-4z"/></svg>
		</button>
      </div>
      <div class="actions">
        <!-- Conditional Reset Button -->
        
        <!-- Hue Value Display -->
        <span class="hue-value-badge">{{ currentHue }}</span>
      </div>
    </div>

    <!-- Bottom Section - Hue Slider -->
    <div class="slider-container">
      <div
        ref="stripRef"
        class="hue-strip"
        @mousedown="startDrag"
        @touchstart.prevent="startDrag"
        @click="handleInteraction"  
      >
        <div
          class="hue-marker"
          :style="{ left: markerPosition }"
        ></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.palette-panel {
  background-color: var(--card-bg-color,#1f1f1f); /* Slightly darker than original for contrast */
  border-radius: 10px; /* Adjusted border-radius */
  padding: 12px 16px; /* Adjusted padding */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
  color: var(--text-color-primary, #e0e0e0);
  width: 280px; /* Keep width or adjust as needed */
  overflow: hidden;
  border: 1px solid var(--border-color, #383838); /* Slightly lighter border */
  user-select: none; /* Prevent text selection on panel */
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px; /* Increased spacing */
}

.title-area {
  display: flex;
  align-items: center;
  gap: 8px; /* Space between indicator and text */
}

.color-indicator-bar {
  display: inline-block;
  width: 4px; /* Slightly thinner bar */
  height: 1.1em; /* Match text size */
  background-color: var(--primary-color); /* Dynamic color from store */
  border-radius: 2px;
  flex-shrink: 0; /* Prevent shrinking */
}

.title-area h4 {
  margin: 0;
  font-size: 0.9em; /* Slightly smaller font */
  font-weight: 500; /* Normal weight */
  white-space: nowrap; /* Prevent wrapping */
  color: #fff;
}

.actions {
  display: flex;
  align-items: center;
  gap: 8px; /* Spacing between buttons/badge */
}

.reset-button {
  background-color: var( rgba(29, 29, 29, 0.1)); /* Subtle background */
  border: none;
  color: var(--text-color-secondary, #b0b0b0); /* Secondary text color */
  border-radius: 6px;
  padding: 4px; /* Smaller padding */
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s ease, color 0.2s ease;
}

.reset-button:hover {
  background-color: var(--button-bg-secondary-hover, rgba(255, 255, 255, 0.12));
  color: var(--text-color-primary, #e0e0e0);
}

.reset-button svg {
  width: 16px; /* Smaller icon */
  height: 16px;
}

.hue-value-badge {
  background-color: var(--badge-bg-color, rgba(255, 255, 255, 0.08)); /* Match button style */
  color: var(--text-color-secondary, #b0b0b0);
  border-radius: 6px;
  padding: 4px 8px; /* Padding for number */
  font-size: 0.8em; /* Small font size */
  font-weight: 600;
  min-width: 28px; /* Ensure minimum width */
  text-align: center;
  font-family: monospace; /* Monospaced font for numbers */
}

.slider-container {
  padding: 2px 0; /* Add minimal vertical padding if needed */
}

.hue-strip {
  width: 100%;
  height: 18px; /* Slightly thinner slider */
  border-radius: 9px; /* Fully rounded ends */
  cursor: pointer;
  position: relative;
  /* The Hue Gradient using defined S/L */
  background: linear-gradient(
    to right,
    hsl(0, 85%, 60%),
    hsl(60, 85%, 60%),
    hsl(120, 85%, 60%),
    hsl(180, 85%, 60%),
    hsl(240, 85%, 60%),
    hsl(300, 85%, 60%),
    hsl(360, 85%, 60%) /* Same as 0 */
  );
  /* outline: 1px solid rgba(255, 255, 255, 0.1); Optional subtle outline */
}

.hue-marker {
  position: absolute;
  top: 50%;
  /* Center the marker based on its own width */
  transform: translate(-50%, -50%);
  width: 10px; /* Smaller marker width */
  height: 22px; /* Taller than the strip */
  background-color: #ffffff;
  border-radius: 3px; /* Less rounded marker */
  /* border: 1px solid rgba(0,0,0,0.2);  Subtle border instead of thick white */
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.1); /* More defined shadow */
  pointer-events: none; /* Prevent marker from intercepting clicks */
  box-sizing: border-box;
}

/* Optional: Style for when dragging */
.hue-strip:active .hue-marker {
   /* background-color: #f0f0f0; */ /* Slightly change marker color on drag */
}
</style>